﻿using System;

using System.Collections.Generic;
using System.Windows.Forms;
using LetsDoIt.BO.ResponseMessages;
using LetsDoIt.Controls;
using LetsDoIt.Interfaces;
using LetsDoIt.BO;
using LetsDoIt.Common;
using System.IO;
using LetsDoIt.Localization;

namespace LetsDoIt.Forms
{
	public partial class ViewCasesForm : UserControl, INavigationForm
	{

		public CaseItem SelectedItem { get; set; }

		#region ctor

		private ViewCasesForm()
		{
			InitializeComponent();
		}

		public ViewCasesForm(MainForm hostForm, string identity)
		{
			HostForm = hostForm;
			Identity = identity;
			InitializeComponent();

		    AddMenusToDictionary();
            
		}

	    #endregion ctor

        protected void AddMenusToDictionary()
        {
            HostForm.AddMenuToDictionary(this.mnuDeleteCase, "ViewCasesForm_DeleteCase");
            HostForm.AddMenuToDictionary(this.mnuEditCase, "ViewCasesForm_EditCase");
            HostForm.AddMenuToDictionary(this.mnuPostCase, "ViewCasesForm_PostCase");
            HostForm.AddMenuToDictionary(this.mnuViewCaseMap, "ViewCasesForm_ViewCaseMap");
        }


		#region Implementation of INavigationForm

		public MainForm HostForm { get; set; }
		public string Identity { get; set; }
        public bool IsActive { get; set; }

		public virtual void NavigationEnter(object sender)
		{
			//
			HostForm.mnuViewCases.Enabled = false;
		    lblStatusMessage.Caption = ResourceManager.Instance.GetString(@"DialogWastePointUploadWait");
		    lblStatusMessage.Visible = false;
		    btnBack.Enabled = true;
			//bind data
			if (sender is IntroForm)
			{
                //
                lblViewCasesTitle.Text = ResourceManager.Instance.GetString("MainForm_lblMaterialsContent_Loading");
				lstCases.Visible = false;
				Application.DoEvents();
				//load only when comming from main screen
				foreach (Control item in lstCases.Items)
				{
					lstCases.RemoveItem(item);
					item.Dispose();
				}
				GC.Collect();
				GC.WaitForPendingFinalizers();
				GC.Collect();
				//
				List<CaseInfo> list = WastesLocalFactory.LoadLocalCases();
				foreach (CaseInfo caseInfo in list)
				{
					CaseItem caseItem = new CaseItem(caseInfo);
					caseItem.ContextMenu = ctxCaseItem;
					caseItem.DoubleClick += new EventHandler(caseItem_DoubleClick);
					lstCases.AddItem(caseItem);
				}
				//
				SelectedItem = null;
				//update context menu
                HostForm.UpdateResources();
                //
			    lblViewCasesTitle.Text = ResourceManager.Instance.GetString("MainForm_lblViewCasesTitle");
				lstCases.Visible = true;
                //
				Application.DoEvents();
			}
		}

		void caseItem_DoubleClick(object sender, EventArgs e)
		{
			GotoSelectedCase();
		}

		public void NavigationLeave()
		{
			//nothing
			HostForm.mnuViewCases.Enabled = true;
		}

		#endregion

        
        #region events

        private void btnBack_Click(object sender, EventArgs e)
		{
			HostForm.NavigateBack(this, string.Empty);
		}

		private void mnuEditCase_Click(object sender, EventArgs e)
		{
			//edit case
			GotoSelectedCase();
		}

		private void GotoSelectedCase()
		{
			if (lstCases.SelectedItems.Count > 0)
			{
				CaseItem caseItem = lstCases.SelectedItems[0] as CaseItem;
				CaseForm caseFrom = HostForm.GetFormByIdentity(NavigationForms.FORM_CASE) as CaseForm;
				if (caseFrom != null && caseItem!=null)
				{
					caseFrom.Mode = WorkMode.Edit;
					caseFrom.ResetCase();
					caseFrom.Case = caseItem.Case;
					HostForm.NavigateTo(this, NavigationForms.FORM_CASE);
					//MessageBox.Show("Edit " + caseItem.Case.ID);
				}
			}
		}

		private void mnuDeleteCase_Click(object sender, EventArgs e)
		{
			//delete case
			if (lstCases.SelectedItems.Count > 0)
			{
				CaseItem caseItem = lstCases.SelectedItems[0] as CaseItem;
                if (caseItem != null)
                {
                    SelectedItem = caseItem;
                    if (
                        MessageBox.Show(
                            ResourceManager.Instance.GetString(@"DialogDeleteCaseConfirmation"), 
                            ResourceManager.Instance.GetString(@"DialogConfirmation"), 
                            MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                    {
                        //delete the case file and pictures from file system
                        WastesLocalFactory.DeleteLocalCase(caseItem.Case.ID);
                        //select previous case
                        SelectCaseAfterDelete(caseItem);
                        //
                        MessageBox.Show(
                            string.Format(ResourceManager.Instance.GetString(@"DialogDeleteCaseConfirmed"), caseItem.Case.ID),
                            ResourceManager.Instance.GetString(@"DialogConfirmation"), 
                            MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                    }
                }
			}
		}

	    private void SelectCaseAfterDelete(CaseItem caseItem)
	    {
            //select previous case
	        int newPos = lstCases.Items.IndexOf(caseItem) - 1;
	        //remove case from list
	        lstCases.RemoveItem(caseItem);
	        //
	        if (newPos >= 0)
	        {
	            lstCases.Items[newPos].Focus();
	            SelectedItem = lstCases.Items[newPos] as CaseItem;
	            if (SelectedItem != null)
	                SelectedItem.SelectedChanged(true);
	        }
	        else
	        {
	            if (lstCases.Items.Count>0)
	            {
	                lstCases.Items[0].Focus();
	                SelectedItem = lstCases.Items[0] as CaseItem;
	                if (SelectedItem != null)
	                    SelectedItem.SelectedChanged(true);
	            }
	            else
	            {
	                SelectedItem = null;
	            }
	        }
	    }

	    private void mnuViewCaseMap_Click(object sender, EventArgs e)
		{
			//view case map
			if (lstCases.SelectedItems.Count > 0)
			{
				CaseItem caseItem = lstCases.SelectedItems[0] as CaseItem;
				SelectedItem = caseItem;
				if(caseItem!=null)
				{
					HostForm.NavigateTo(this, NavigationForms.FORM_CASE_MAP);
				}
			}
		}

		private void mnuPostCase_Click(object sender, EventArgs e)
		{
            //disable UI
		    HostForm.SuspendMenu();
            btnBack.Enabled = false;
            //
		    //lblStatusMessage.Text = "Please wait ...";
		    lblStatusMessage.Visible = true;
		    lstCases.Enabled = false;
            //show dialog
            //string dialogKey = CustomDialog.ShowDialog(HostForm, 
            //    "Posting case", 
            //    "Posting selected case", null, null, 0 );
            Application.DoEvents();

			//post selected case
            try
            {
                if (lstCases.SelectedItems.Count > 0)
                {
                    CaseItem caseItem = lstCases.SelectedItems[0] as CaseItem;
                    SelectedItem = caseItem;
                    if (caseItem != null && caseItem.Case != null)
                    {
                        CaseInfo caseInfo = caseItem.Case;
                        //
                        //progressBarUploadEx.Text = ResourceManager.Instance.GetString(@"MainForm_ProgressBar_Connecting");
                        //Application.DoEvents();
                        //
                        if (string.IsNullOrEmpty(AuthServiceFactory.GetInstallationId()))
                        {
                            MessageBox.Show(
                                ResourceManager.Instance.GetString(@"DialogWebConnectError"),
                                ResourceManager.Instance.GetString(@"DialogErrorTitle"),
                                MessageBoxButtons.OK, MessageBoxIcon.Hand, MessageBoxDefaultButton.Button1);
                        }
                        else
                        {
                            string username = HostForm.Settings.UserName;
                            string salt = AuthServiceFactory.GetUserSalt(username);
                            string md5pass = Utils.Utils.GetPassHash(HostForm.Settings.Password + salt);
                            if (AuthServiceFactory.ValidateUser(username, md5pass))
                            {
                                bool isCaseUploadError = false;
                                ResponseWaste responseWaste = WastesServiceFactory.UploadCase(caseInfo, username, md5pass, HostForm.Settings.UploadDataAsTest);
                                if (responseWaste == null || !responseWaste.Succes)
                                {
                                    //fail
                                    MessageBox.Show(
                                        string.Format(ResourceManager.Instance.GetString(@"DialogUploadErrorAbort"),
                                                      caseInfo.ID),
                                        ResourceManager.Instance.GetString(@"DialogErrorTitle"),
                                        MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
                                        MessageBoxDefaultButton.Button1);
                                }
                                else
                                {
                                    //succes - continue with pictures
                                    if (caseInfo.Pictures != null)
                                    {
                                        List<string> lstToUpload = new List<string>(caseInfo.Pictures);
                                        lstToUpload.Reverse();
                                        foreach (string picture in lstToUpload)
                                        {
                                            //countProgress++;
                                            //progressBarUploadEx.Value = countProgress;
                                            //Application.DoEvents();
                                            //
                                            string pictureFile = Path.Combine(WastesLocalFactory.CasesStorePath(),
                                                                              picture);
                                            if (File.Exists(pictureFile))
                                            {
                                                ResponseImage responseImage =
                                                    WastesServiceFactory.UploadImage(pictureFile, responseWaste.ServerID,
                                                                                     username, md5pass);
                                                if (responseImage == null || !responseImage.Succes)
                                                {
                                                    isCaseUploadError = true;
                                                    if (MessageBox.Show(
                                                            string.Format(
                                                                ResourceManager.Instance.GetString(
                                                                    @"DialogUploadImageErrorAbort"), caseInfo.ID),
                                                            ResourceManager.Instance.GetString(@"DialogErrorTitle"),
                                                            MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation,
                                                            MessageBoxDefaultButton.Button2) ==
                                                        DialogResult.Yes)
                                                    {
                                                        break;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                MessageBox.Show(string.Format(
                                                                    ResourceManager.Instance.GetString(
                                                                        @"DialogUploadErrorImageNotAvailable"),
                                                                    pictureFile));
                                            }
                                        }
                                    }

                                    //cleanup
                                    if (!isCaseUploadError)
                                    {
                                        //delete the case file and pictures from file system
                                        WastesLocalFactory.DeleteLocalCase(caseInfo.ID);
                                        //select previous case
                                        SelectCaseAfterDelete(caseItem);
                                    }
                                }
                            }
                            else
                            {
                                //user credentials invalid
                                MessageBox.Show(
                                    ResourceManager.Instance.GetString(@"DialogLoginInvalidError"),
                                    ResourceManager.Instance.GetString(@"DialogErrorTitle"),
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
                            }
                        }
                    }
                }
            }
            catch(Exception ex)
		    {
                Program.Log.Error(ex.ToString());
		        MessageBox.Show("Unexpected error");
		    }

            lblStatusMessage.Visible = false;
            lstCases.Enabled = true;
            //hide dialog
            //CustomDialog.HideDialog(dialogKey);
		    //enable UI
            HostForm.ResumeMenu();
            btnBack.Enabled = true;
            Application.DoEvents();
        }

        #endregion events

    }
}
